import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.*;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;

import org.json.JSONException;
import org.json.JSONObject;

import DataType.MessageFormat;

import com.google.gson.*;

public class TemperatureSensor extends VirtualSensor {
	private HashMap<String, String> bodyCopies;

	TemperatureSensor(VSensorConfig vs, SocketSender sender) {
		super(vs, sender);
		bodyCopies = new HashMap<String, String>(100);
	}

	protected String prepareJsonStr() {

		String str = TemperatureData.getCurrentDateTime("2012-03-11", 3000);
		String value = TemperatureData.getCurrentTemperature(str);
		bodyCopies.put("SensorId", String.valueOf(config.getSensorID()));
		bodyCopies.put("Value", value);
		bodyCopies.put("DcTime", str);
		Gson gson = new Gson();
		JsonObject jsonobject = new JsonObject();
		for (String strKey : bodyCopies.keySet()) {
			value = bodyCopies.get(strKey);
			jsonobject.addProperty(strKey, value);
		}
		String jsonStr = gson.toJson(jsonobject);
		bodyCopies.clear();
		return jsonStr;
	}

	@Override
	public void run() {
		try {

			String path = System.getProperty("user.dir");
			String path1 = path + "/weatherdata.txt";
			String path2 = path + "/sensordata.txt";
			TemperatureData.fillTemperatureData(path1, path2);
			while (!this.isInterrupted()) {
				if (sender.isAlive()) {
					List<ByteBuffer> bufferList = sender.getBufferList();
					synchronized (bufferList) {
						ByteBuffer bb = prepareData();
						bufferList.add(bb);
						bufferList.notify();
					}
					System.out.println("Config.getGenerateRate = "
							+ config.getGenerate_rate());
				} else
					break;
				Thread.sleep(config.getGenerate_rate());

			}
		} catch (InterruptedException e) {
			System.out.println(Thread.currentThread().getName()
					+ " interrupted");
			// e.printStackTrace();
		}
	}
}
